from django.http import HttpResponse, JsonResponse
from django.views import View


# Create your views here.
class ImageCodeView(View):
    def get(self,request,uuid):

        from libs.captcha.captcha import captcha
        #text是验证码字符串，image是验证码图片二进制数据
        text, image = captcha().generate_captcha()
        #把验证码字符串保存到session中
        from django_redis import get_redis_connection
        #连接redis
        redis_cli = get_redis_connection('code')
        #设置验证码有效期
        redis_cli.setex(uuid, 300, text)
        #返回验证码图片
        return HttpResponse(image,content_type='image/jpeg')

class SmsCodeView(View):
    def get(self,request,mobile):

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        if not all([image_code,uuid]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        from django_redis import get_redis_connection
        redis_cli = get_redis_connection('code')
        redis_image_code = redis_cli.get(uuid)
        if  redis_image_code is None:
            return JsonResponse({'code':400,'errmsg':'图片验证码失效'})

        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({'code':400,'errmsg':'图片验证码错误'})
        send_flag = redis_cli.get('send_flag_%s' % mobile)

        if send_flag is not None:
            return JsonResponse({'code':400,'errmsg':'发送短信过于频繁'})

        from random import randint
        sms_code = '%04d'%randint(0,9999)
        #管道技术
        pipeline = redis_cli.pipeline()
        pipeline.setex(mobile, 300, sms_code)
        pipeline.setex('send_flag_%s'%mobile, 60, 1)
        pipeline.execute()
        # redis_cli.setex(mobile, 300, sms_code)
        # redis_cli.setex('send_flag_%s'%mobile, 60, 1)

        # from libs.yuntongxun.sms import CCP
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        from celery_tasks.sms.tasks import celery_send_sms_code
        celery_send_sms_code.delay(mobile,sms_code)
        return JsonResponse({'code':0,'errmsg':'短信验证码发送成功'})